// miniprogram/pages/orders/index.js
const { sendCmd } = require('../../utils/sendCmds.js');
const { queryOrder } = require('../../utils/checkTimeout.js');
const { queryDownOrder } = require('../../utils/checkDown.js');
const API_KEY = getApp().globalData.API_KEY;
const deviceId = getApp().globalData.deviceId;
import Dialog from '@vant/weapp/dialog/dialog';
const db = wx.cloud.database();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orders:[],
    userData:{},
    orderType:''
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    wx.showLoading({
      title: '正在加载',
    })
    switch (options.orderType) {
      case 'all':
        wx.setNavigationBarTitle({title: '全部订单'});
        this.queryOrders();
        wx.hideLoading();
        break;
      case 'will':
        wx.setNavigationBarTitle({title: '预约订单'});
        this.queryOrders({orderType:'will'});
        wx.hideLoading();
        break;
      case 'going':
        wx.setNavigationBarTitle({title: '进行中订单'});
        this.queryOrders({orderType:'going'});
        wx.hideLoading();
        break;
      case 'down':
        wx.setNavigationBarTitle({title: '已完成订单'});
        this.queryOrders({orderType:'down'});
        wx.hideLoading();
        break;
      case 'timeout':
        wx.setNavigationBarTitle({title: '逾期订单'});
        this.queryOrders({orderType:'timeout'});
        wx.hideLoading();
        break;
    }
    this.setData({ userData:wx.getStorageSync('userData'),orderType:options.orderType });
  },

  getLocalTime(timestemp) {     
    return new Date(timestemp).toLocaleString().replace(/:\d{1,2}$/,' ');     
  },

  queryOrders(query){
    const that = this;
    const userInfo = wx.getStorageSync('userInfo');
    db.collection('orders').orderBy('timestemp','desc').where({
       _openid: userInfo.openId,
       ...query
    }).get({
      success: res => {
        let orders = res.data;
        orders.map(v=>{
          v.timestemp = that.getLocalTime(v.timestemp);
          if (v.endTimestemp !== null) {
            v.endTimestemp = that.getLocalTime(v.endTimestemp);
          }
        })
        that.setData({ orders });
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })
  },

  deleteOrder(e){
    const that = this;
    Dialog.confirm({
      title: '取消预约',
      message: '您确定要取消预约吗？',
    }).then(() => {
      db.collection('orders').doc(e.currentTarget.dataset.id).remove({
        success: res => {
          wx.showToast({
            title: '删除成功',
            duration:1000,
            mask:true,
            success(){
              setTimeout(() => {
                wx.switchTab({
                  url: '/pages/my/index',
                })
              }, 1000);      
            }
          })
        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '删除失败',
          })
          console.error('[数据库] [删除记录] 失败：', err)
        }
      })
    }).catch(() => {
      console.log('取消操作');
    });
  },


  endOrder(e){
    const that = this;
    Dialog.confirm({
      title: '结束订单',
      message: '您确定要提前结束订单吗？',
    }).then(() => {
      sendCmd(deviceId,API_KEY,{"SET":"STOP"});
      db.collection('orders').doc(e.currentTarget.dataset.id).update({
        data:{
          orderType:'down',
          endTimestemp:(new Date()).valueOf()
        },
        success: res => {
          wx.showToast({
            title: '结束成功',
            duration:1000,
            mask:true,
            success(){
              setTimeout(() => {
                wx.switchTab({
                  url: '/pages/my/index',
                })
              }, 1000);      
            }
          })
        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '操作失败',
          })
          console.error('[数据库] [更新记录] 失败：', err)
        }
      })
    }).catch(() => {
      console.log('取消操作');
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    const orderType = this.data.orderType;
    queryDownOrder();
    queryOrder();
    if (orderType === 'all') {
      this.queryOrders();
    }else{
      this.queryOrders({ orderType:orderType });
    }
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})